package com.frxuexi.visit.view

import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.frxuexi.lib_base.entity.StatusBean
import com.frxuexi.lib_base.entity.VisitBeanItem
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.visit.R
import com.frxuexi.visit.VisitIntent
import com.frxuexi.visit.VisitViewModel
import com.frxuexi.visit.adapter.StatusAdapter
import com.frxuexi.visit.adapter.VisitAdapter
import com.frxuexi.visit.databinding.ActivityVisitBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/visit/VisitActivity")
@AndroidEntryPoint
class VisitActivity : BaseActivity<ActivityVisitBinding, VisitIntent, VisitViewModel>() {
    override val binding: ActivityVisitBinding by lazy { ActivityVisitBinding.inflate(layoutInflater) }
    override val vm: VisitViewModel by viewModels<VisitViewModel>()
    val visitAdapter by lazy { VisitAdapter() }
    val statusAdapter by lazy { StatusAdapter() }

    var position = -1

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                val items = it.data as Collection<VisitBeanItem>
                                if (items.size == 0) {
                                    vm.sendIntent(VisitIntent.getVisitByPurpose(binding.visitSv.text.toString()))
                                } else {
                                    visitAdapter.apply {
                                        data.clear()
                                        addData(items.sortedByDescending { it.id })
                                        notifyDataSetChanged()
                                    }
                                }
                            }

                            RequestType.DELETE -> {
                                visitAdapter.data.removeAt(position)
                                visitAdapter.notifyItemRemoved(position)
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }

    }

    override fun initView() {
        binding.visitRv.apply {
            adapter = visitAdapter
            layoutManager = LinearLayoutManager(this@VisitActivity)
        }

        val status = listOf<StatusBean>(
            StatusBean("全部状态", true),
            StatusBean("已通过", false),
            StatusBean("驳回", false)
        )
        statusAdapter.addData(status)
        binding.visitRvStatus.apply {
            adapter = statusAdapter
            layoutManager = LinearLayoutManager(this@VisitActivity, RecyclerView.HORIZONTAL, false)
        }
        statusAdapter.setOnItemClickListener { adapter, view, position ->
            statusAdapter.data.forEach {
                it.checked = false
            }
            statusAdapter.data.get(position).checked = true
            statusAdapter.notifyDataSetChanged()

            if (position == 0) {
                vm.sendIntent(VisitIntent.getVisits)
            } else {
                vm.sendIntent(VisitIntent.getVisitByStatus(status.get(position).content.toString()))
            }
        }

        binding.visitSv.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s.isNullOrEmpty()) {
                    vm.sendIntent(VisitIntent.getVisits)
                } else {
                    vm.sendIntent(VisitIntent.getVisitByName(s.toString()))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        visitAdapter.setOnItemLongClickListener { adapter, view, position ->
            this.position = position
            val item = visitAdapter.data.get(position)
            AlertDialog.Builder(this)
                .setTitle("删除确认").setMessage("是否删除${item.visitorName}的来访吗？")
                .setPositiveButton("确认", object : OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        vm.sendIntent(VisitIntent.deleteVisit(item.id!!))
                    }
                })
                .setNegativeButton("取消", null)
                .create()
                .show()
            return@setOnItemLongClickListener true
        }

        binding.visitAdd.setOnClickListener {
            ArouterManager.nav(this, "/visit/VisitAddActivity")
        }

        visitAdapter.setOnItemClickListener { adapter, view, position ->
            ArouterManager.nav(
                this,
                "/visit/VisitApproveActivity",
                visitAdapter.data.get(position).id!!
            )
        }


    }

    override fun onResume() {
        super.onResume()
        val content = statusAdapter.data.filter { it.checked }.get(0).content
        if (content == "全部状态")
            vm.sendIntent(VisitIntent.getVisits)
        else
            vm.sendIntent(VisitIntent.getVisitByStatus(content.toString()))
    }

}